package com.free.bsf.sentinel;

import com.free.bsf.core.base.BsfException;
import com.free.bsf.core.base.Ref;
import com.free.bsf.core.util.PropertyUtils;
import com.free.bsf.sentinel.base.SphEntry;
import lombok.val;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class SentinelFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        val request = (HttpServletRequest) servletRequest;
        //val response = (HttpServletResponse) servletResponse;
        val uri = request.getRequestURI();
        val includeResource = PropertyUtils.getPropertyCache(SentinelProperties.BsfSentinelWebIncludeResource,"");
        boolean isInclude = SentinelUtils.isLikeMatch(uri,includeResource.replace("web:","").split(";"));
        if(isInclude) {
            Ref<Exception> ex = new Ref<>(null);
            SentinelUtils.run(new SphEntry().setName("web:" + uri), () -> {
                try {
                    chain.doFilter(servletRequest, servletResponse);
                } catch (Exception e) {
                    ex.setData(e);
                }
            });
            if (ex.getData() != null) {
                throw new BsfException(ex.getData());
            }
        }else{
            chain.doFilter(servletRequest, servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}
